package com.demo.common.exception;


import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * @version 1.0 异常基类
 */

public class BaseException extends RuntimeException {

    public static final int UNKNOWN_ERROR_CODE = 9999;//未知错误code
    private Throwable cause;//异常
    private int errorCode;//错误code
    private Object[] args;//扩展值

    public BaseException(int errorCode, Object... args) {
        this(errorCode, "", args);
    }

    public BaseException(int errorCode, String errorMsg, Object... args) {
        this(null, errorCode, errorMsg, args);
    }

    public BaseException(Throwable cause, Object... args) {
        this(cause, "", args);
    }

    public BaseException(Throwable cause, String errorMsg, Object... args) {
        this(cause, BaseException.UNKNOWN_ERROR_CODE, errorMsg, args);
    }

    public BaseException(Throwable cause, Integer errorCode, String errorMsg, Object... args) {
        super(errorMsg);
        this.cause = cause;
        this.errorCode = errorCode;
        this.args = args;
    }

    public void printStackTrace() {
        this.printStackTrace(System.err);
    }

    public void printStackTrace(PrintStream ps) {
        if (null == getCause()) {
            super.printStackTrace(ps);
        } else {
            ps.println(this);
            getCause().printStackTrace(ps);
        }
    }

    public void printStackTrace(PrintWriter pw) {
        if (null == getCause()) {
            super.printStackTrace(pw);
        } else {
            pw.println(this);
            getCause().printStackTrace(pw);
        }
    }

    public Throwable getCause() {
        return this.cause == this ? null : this.cause;
    }

    public String getMessage() {
        if (getCause() == null) {
            return super.getMessage();
        }
        return super.getMessage() + getCause().getMessage();
    }

    public int getErrorCode() {
        return errorCode;
    }

    public String getArgs() {
        if (args == null) {
            return "";
        }
        return Arrays.toString(args);
    }

}

